package com.anlu.paypal.service.impl;

import com.anlu.paypal.service.PaymentV2Service;
import com.anlu.paypal.utils.PayPalClient;
import com.anlu.paypal.utils.PayPalRESTException;
import com.anlu.paypal.utils.PayPalSubmit;
import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class PaymentV2ServiceImpl implements PaymentV2Service {
    @Value("${paypal.client.app}")
    public  String clientId ;

    @Value("${paypal.client.secret}")
    public  String secret ;

    @Value("${paypal.mode}")
    public  String mode ;
    /**
     * 支付的方法
     * @param totalMoney 总金额
     * @param currency 货币类型
     * @param cancelUrl 取消的url
     * @param successUrl 成功的url
     * @return
     * @throws PayPalRESTException
     */
    @Override
    public String createPayment(String totalMoney,
                                String currency,
                                String cancelUrl,
                                String successUrl) throws PayPalRESTException {

            PayPalClient payPalClient = new PayPalClient();
            // 设置环境沙盒或生产
            PayPalHttpClient client = payPalClient.client(mode, clientId, secret);
            //回调参数
            Map<String, String> sParaTemp = new HashMap<String, String>();
            //回调的参数 可以多设置几个
            sParaTemp.put("totalMoney", totalMoney);
            String url = successUrl + paramsConvertUrl(sParaTemp);
            // 配置请求参数
            OrderRequest orderRequest = new OrderRequest();
            orderRequest.checkoutPaymentIntent("CAPTURE");
            List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
            purchaseUnits.add(new PurchaseUnitRequest().amountWithBreakdown(new AmountWithBreakdown().currencyCode(currency).value(totalMoney)));
            orderRequest.purchaseUnits(purchaseUnits);
            orderRequest.applicationContext(new ApplicationContext().returnUrl(url).cancelUrl(cancelUrl));
            OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);
            HttpResponse<Order> response;
            try {
                response = client.execute(request);
                Order order = response.result();
                String token = order.id();
                String payHref = null;
                String status = order.status();
                if (status.equals("CREATED")) {
                    List<LinkDescription> links = order.links();
                    for (LinkDescription linkDescription : links) {
                        if (linkDescription.rel().equals("approve")) {
                            payHref = linkDescription.href();
                        }
                    }
                }
                Map<String, String> resultMap = new HashMap<String, String>();
                resultMap.put("token", token);
                return PayPalSubmit.buildRequest(resultMap,payHref, "get", "确认");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private static String paramsConvertUrl(Map<String, String> params) {
            StringBuilder urlParams = new StringBuilder("?");
            Set<Map.Entry<String, String>> entries = params.entrySet();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            String urlParamsStr = urlParams.toString();
            return urlParamsStr.substring(0, urlParamsStr.length()-1);
        }

}
